package com.example.grid.webserviceclient;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.Toast;


import org.apache.commons.io.IOUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * @author LiuYi
 *         创建时间： 2017/10/9.
 *         功能描述:
 */

public class MethodListActivity extends AppCompatActivity implements View.OnClickListener,ActivityCompat.OnRequestPermissionsResultCallback  {
    private String TAG = "SimpleWebService";
    private EditText edtInputParam;
    protected List<String> mMethodList = new ArrayList<>();
    protected List<String> mEncodeList = new ArrayList<>();
    private String mSelectedMethodName = "";
    private String  mXmPrara="";
    private String mEncode="UTF-8";
    private int PERMISSIONS_REQUEST_CODE=0x0101;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE" };
   private static String dataPath="mnt/sdcard/51共享目录/data.txt";
    //private static String dataPath ="sdcard/Download/data.txt";


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_methodlist);
        initList();
        initView();
        if (storagePermissionsIsGranted()){
          readFileFromSdcard();
        }
    }

    //读sdCard
    private void readFileFromSdcard()
    {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "此时SDcard不存在或者不能进行读写操作", Toast.LENGTH_SHORT).show();
            return;
        }

        Observable<Object> observable = Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                File file = new File(dataPath);
                InputStream inputStream=null;
                try {
                    inputStream= new java.io.FileInputStream(file);
                    String string =inputStream2String(inputStream,mEncode);
                    emitter.onNext(string);
                    emitter.onComplete();
                } catch (Exception e) {
                    if ( inputStream !=null){
                        inputStream.close();
                    }
                    emitter.onError(e);
                }

            }
        });

        //创建一个下游 Observer
        Observer<Object> observer = new Observer<Object>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(Object value) {
                if (value instanceof String) {
                    mXmPrara = (String) value;
                    edtInputParam.setText(mXmPrara);
                    Toast.makeText(MethodListActivity.this, "读取文件成功", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onError(Throwable e) {
                Toast.makeText(MethodListActivity.this, "读取失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete() {
            }
        };

        observable.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);

    }

    public String inputStream2String(InputStream is,String encode)   throws   IOException{
        try {
            String text = IOUtils.toString(is, encode);
            is.close();
            return text;
        }catch (Exception e){
            return "";
        }
    }

    public  boolean  storagePermissionsIsGranted() {
        try {
            return  ActivityCompat.checkSelfPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE")==PackageManager.PERMISSION_GRANTED;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private void initList() {
        //接口列表
        mMethodList.add("GetBasInfo");
        mMethodList.add("NeonatalScreening");
        mMethodList.add("PopulationIndex");
        mMethodList.add("GetPrescInfo");
        mMethodList.add("GetInpBilledDetailInfo");
        mMethodList.add("GetAllowance");
        mMethodList.add("GetOutAppointment");
        mMethodList.add("GetInfectionCard");
        mMethodList.add("GetExamInfo");
        mMethodList.add("downloadZZRecords");//国家跨省新农合接口
        mMethodList.add("uploadInpRegister");
        mMethodList.add("cancelInpRegister");
        mMethodList.add("uploadInpDetails");
        mMethodList.add("clearInpDetails");
        mMethodList.add("preInpPay");
        mMethodList.add("inpPay");
        mMethodList.add("backPay");

        //编码方式列表
        mEncodeList.add("UTF-8");
        mEncodeList.add("UTF-16");
        mEncodeList.add("GB2312");
        mEncodeList.add("GBK");
    }

    private void initView() {
        edtInputParam = (EditText) findViewById(R.id.edtInputParam);
        //选择方法
        Spinner spinner = (Spinner) findViewById(R.id.spinnerMethod);
        spinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, mMethodList));
        spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                mSelectedMethodName = mMethodList.get(arg2);
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });

        //spinnerEncode
        Spinner spinnerEncode = (Spinner) findViewById(R.id.spinnerEncode);
        spinnerEncode.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, mEncodeList));
        spinnerEncode.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                mEncode = mEncodeList.get(arg2);
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });

        findViewById(R.id.btnCallMethod).setOnClickListener(this);
        findViewById(R.id.btnRefreshFile).setOnClickListener(this);
    }

    private void toCallMethodActivity() {
        String inputString = mXmPrara;
        try {
            Intent intent = new Intent(MethodListActivity.this, CallSSLWebServiceActivity.class);
            intent.putExtra("methodName", mSelectedMethodName);
            intent.putExtra("xmlParam", inputString);
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(this, "编码转换错误", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnCallMethod://调用方法
                if (TextUtils.isEmpty(edtInputParam.getText().toString())) {
                    Toast.makeText(this, "填入xml参数", Toast.LENGTH_SHORT).show();
                    break;
                }

                if (TextUtils.isEmpty(mSelectedMethodName)) {
                    Toast.makeText(this, "请选择调用的方法", Toast.LENGTH_SHORT).show();
                    break;
                }
                toCallMethodActivity();
                break;

            case R.id.btnRefreshFile:
                if (storagePermissionsIsGranted()){
                    readFileFromSdcard();
                }else{
                    ActivityCompat.requestPermissions(this,PERMISSIONS_STORAGE,PERMISSIONS_REQUEST_CODE);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,@NonNull int[] grantResults){
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode != PERMISSIONS_REQUEST_CODE) {
            return;
        }

        if (grantResults.length > 0) {
            readFileFromSdcard();
        }
    }
}
